package com.lindroy.androidplayer.base

import android.annotation.SuppressLint
import android.app.Application
import android.content.Context
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.ViewModelStoreOwner
import com.elvishew.xlog.LogConfiguration
import com.elvishew.xlog.LogLevel
import com.elvishew.xlog.XLog
import com.elvishew.xlog.formatter.border.DefaultBorderFormatter
import com.lindroy.androidplayer.BuildConfig
import com.lindroy.androidplayer.R
import com.lindroy.multistatelayout.MultiStateLayout
import com.elvishew.xlog.internal.SystemCompat
import com.elvishew.xlog.printer.AndroidPrinter
import com.lindroy.androidplayer.logic.network.enums.LayoutState
import com.tencent.mmkv.MMKV


/**
 * @author Lin
 * @date 2022/1/7
 * @function
 */
class App : Application(), ViewModelStoreOwner {

    private val appViewModelProvider by lazy {
        ViewModelProvider(
            this,
            ViewModelProvider.AndroidViewModelFactory.getInstance(this)
        )
    }

    override fun getViewModelStore(): ViewModelStore = ViewModelStore()

    companion object {
        @SuppressLint("StaticFieldLeak")
        @JvmStatic
        lateinit var context: Context
            private set
        lateinit var eventViewModel: EventViewModel
            private set
    }

    override fun onCreate() {
        super.onCreate()
        context = applicationContext
        eventViewModel = appViewModelProvider[EventViewModel::class.java]
        initStateLayout()
        initLogger()

        MMKV.initialize(this)
    }

    private fun initLogger() {
        XLog.init(
            LogConfiguration.Builder()
                .logLevel(if (BuildConfig.DEBUG) LogLevel.ALL else LogLevel.NONE)
                .tag("PlayTag")
                .enableBorder()
                .build(),
            AndroidPrinter(true)    //解决边框线不对齐的问题
        )
    }

    private fun initStateLayout() {
        MultiStateLayout.init()
            .setLoadingView(R.layout.layout_loading)
            .setEmptyView(
                R.layout.layout_empty_view,
                R.id.tvEmpty,
                getString(R.string.layout_state_empty)
            )
            .setErrorView(
                R.layout.layout_server_error,
                clickViewIds = intArrayOf(R.id.btnServerError)
            )
            .setNoNetworkView(
                R.layout.layout_no_network,
                clickViewIds = intArrayOf(R.id.btnNoNetwork)
            )
            .addStateView(LayoutState.NOT_LOGIN,R.layout.layout_not_login,R.id.btnLogin)

    }

}